package com.thinkwide.data.vdata;

import com.thinkwide.data.exchange.MFXml;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Iterator;

public class MFDataItems extends ArrayList<MFDataItem> {
    public boolean loadFromXml(String xml) {
        Document doc = MFXml.string2Document(xml);
        Element root = doc.getRootElement();

        for (Iterator<?> i = root.elementIterator(); i.hasNext(); ) {
            MFDataItem item = new MFDataItem();
            Element elem = (Element) i.next();
            item.setTitle(MFXml.getAttrValue(elem, "title"));
            item.setField(MFXml.getAttrValue(elem, "field"));
            item.setWidth(MFXml.getAttrValue(elem, "width"));
            item.setDataType(MFXml.getAttrValue(elem, "dataType"));
            item.setViewType(MFXml.getAttrValue(elem, "viewType"));
            item.setJs(MFXml.getAttrValue(elem, "js"));
            item.setVisible(MFXml.getAttrValue(elem, "visible"));
            item.setEnable(MFXml.getAttrValue(elem, "enable"));

            this.add(item);
        }

        return true;
    }

    public String SaveToXml() {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("data");
        for (MFDataItem item : this) {
            Element node = root.addElement("item");
            node.addAttribute("title", item.getTitle());
            node.addAttribute("field", item.getField());
            node.addAttribute("width", item.getWidth());
            node.addAttribute("dataType", item.getDataType());
            node.addAttribute("viewType", item.getViewType());
            node.addAttribute("js", item.getJs());
            node.addAttribute("visible", item.getVisible());
            node.addAttribute("enable", item.getEnable());

        }

        return doc.asXML();
    }
}
